//
//  ViewController.m
//  NSOperation图片获取
//
//  Created by Justsoso on 16/3/24.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityView;
@property (nonatomic,strong) NSArray *arr;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.arr = @[@"http://www.apple.com.cn/mac-pro/images/static/processor.jpg",@"http://www.apple.com.cn/mac-pro/images/static/memory.jpg",@"http://www.apple.com.cn/mac-pro/images/static/graphics.jpg",@"http://www.apple.com.cn/mac-pro/images/static/storage.jpg",@"http://www.apple.com.cn/mac-pro/images/static/thermal.jpg",@"http://www.apple.com.cn/mac-pro/images/static/fan.jpg",@"http://www.apple.com.cn/mac-pro/images/static/expansion.jpg",@"http://www.apple.com.cn/mac-pro/images/static/wifi.jpg",@"http://www.apple.com.cn/mac-pro/images/static/design.jpg",@"http://www.apple.com.cn/mac-pro/images/static/comingsoon.jpg"];
}
- (IBAction)btn1Pressed:(id)sender
{
    [self.activityView startAnimating];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 10;
    [self download:queue];
    
}


- (IBAction)btn2Pressed:(id)sender
{
    [self.activityView startAnimating];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 1;
    
    [self download:queue];
    
    
}

- (void)download:(NSOperationQueue *)queue
{
    
    for (int i=0; i<self.arr.count; i++)
    {
        NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
            // 网址对象
            NSURL *url = [NSURL URLWithString:self.arr[i]];
            // 获取数据
            NSData *data = [NSData dataWithContentsOfURL:url];
            // 图像对象
            UIImage *image = [UIImage imageWithData:data];
            // 图像视图
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
                imgView.frame = CGRectMake((i%3)*100+35, (i/3)*100+200, 100, 100);
                // 添加到视图
                [self.view addSubview:imgView];
            }];
            
        }];
        [queue addOperation:op];
    }
}

@end
